package com.study.jsqlparser;

import com.study.jsqlparser.dto.SlowQueryMetadata;
import com.study.jsqlparser.utils.FileUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class SlowQueryAnalysis4xinao {
    @SneakyThrows
    public static void main(String[] args) {
//        statistics4Directory();
        statistics4File();
    }


    private static void statistics4File() throws IOException {
        List<String> list = FileUtils.readFileByLine(new File("E:\\xinao\\sql优化\\0516慢SQL已分割\\sql\\slow_page1.log"));
        log.info("从文件中读取到的总行数:{}", list.size());
        List<SlowQueryMetadata> slowQueryMetadataList = getSqlDTOList(list, "slow_page1.sql");
        log.info("提取出了:{}条sql", slowQueryMetadataList.size());
        HashSet<SlowQueryMetadata> set = new HashSet<>(slowQueryMetadataList);
        log.info("去重后的sql条数:{}", set.size());
        Map<String, List<SlowQueryMetadata>> map = set.stream().filter(item -> StringUtils.hasText(item.getAppName())).collect(Collectors.groupingBy(SlowQueryMetadata::getAppName));
        for (Map.Entry<String, List<SlowQueryMetadata>> entry : map.entrySet()) {
            String key = entry.getKey();
            List<SlowQueryMetadata> value = entry.getValue();
            List<String> collect = value.stream().sorted(Comparator.comparingInt(SlowQueryMetadata::getCount).reversed()).map(SlowQueryMetadata::toString).collect(Collectors.toList());
            FileUtils.write2File(new File(key + ".sql"), collect);
        }
        Collection<List<SlowQueryMetadata>> values = map.values();
        List<String> all = new ArrayList<>();
        for (List<SlowQueryMetadata> value : values) {
            value.sort(Comparator.comparingInt(SlowQueryMetadata::getCount).reversed());
            for (SlowQueryMetadata slowQueryMetadata : value) {
                all.add(slowQueryMetadata.toString());
            }
        }
        FileUtils.write2File(new File("allx.sql"), all);
    }


    private static void statistics4Directory() throws IOException {
        Set<SlowQueryMetadata> set = new HashSet<>();
        for (File file : new File("E:\\xinao\\sql优化\\0516慢SQL已分割\\sql\\").listFiles()) {
            String fileName = file.getName();
            log.info(fileName);
            List<String> list = FileUtils.readFileByLine(file);
            log.info("从文件中读取到的总行数:{}", list.size());
            List<SlowQueryMetadata> slowQueryMetadataList = getSqlDTOList(list, fileName);
            log.info("提取出了:{}条sql", slowQueryMetadataList.size());
            set.addAll(slowQueryMetadataList);
        }
        log.info("去重后的sql条数:{}", set.size());
        Map<String, List<SlowQueryMetadata>> map = set.stream().filter(item -> StringUtils.hasText(item.getAppName())).collect(Collectors.groupingBy(SlowQueryMetadata::getAppName));
        for (Map.Entry<String, List<SlowQueryMetadata>> entry : map.entrySet()) {
            String key = entry.getKey();
            List<SlowQueryMetadata> value = entry.getValue();
            List<String> collect = value.stream().map(SlowQueryMetadata::toString).collect(Collectors.toList());
            FileUtils.write2File(new File("E:\\xinao\\sql优化\\0516慢SQL已分割\\去重并分类\\" + key + ".sql"), collect);
        }
        Collection<List<SlowQueryMetadata>> values = map.values();
        List<String> all = new ArrayList<>();
        for (List<SlowQueryMetadata> value : values) {
            for (SlowQueryMetadata slowQueryMetadata : value) {
                all.add(slowQueryMetadata.toString());
            }
        }
        FileUtils.write2File(new File("E:\\xinao\\sql优化\\0516慢SQL已分割\\去重并分类\\allx.sql"), all);


    }

    private static List<SlowQueryMetadata> getSqlDTOList(List<String> list, String fileName) {
        List<SlowQueryMetadata> slowQueryMetadataList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String line = list.get(i);
            if (!StringUtils.hasText(line)) {
                continue;
            }
            if (line.trim().startsWith("# Time:")) {
                SlowQueryMetadata slowQueryMetadata = new SlowQueryMetadata();
                slowQueryMetadata.setFileName(fileName);
                slowQueryMetadataList.add(slowQueryMetadata);
                slowQueryMetadata.setTime(line);
                boolean multilineComment = false;
                while (i < list.size() - 1) {
                    i++;
                    line = list.get(i);
                    // 处理多行注释
                    if (line.trim().contains("/*")) {
                        multilineComment = true;
                        continue;
                    }
                    if (line.trim().contains("*/")) {
                        multilineComment = false;
                        continue;
                    }
                    if (multilineComment) {
                        continue;
                    }
                    if (line.trim().startsWith("# Time:")) {
                        i--;
                        break;
                    }
                    if (line.startsWith("# User@Host:")) {
                        slowQueryMetadata.setUserAndHost(line);
                        evaluationAppName(line, slowQueryMetadata);
                    }
                    if (line.startsWith("# Schema:")) {
                        slowQueryMetadata.setSchema(line);
                    }
                    if (line.startsWith("# Query_time:")) {
                        slowQueryMetadata.setQueryTime(line);
                    }
                    if (line.startsWith("# Bytes_sent:")) {
                        slowQueryMetadata.setBytesSent(line);
                    }
                    if (line.startsWith("SET timestamp=")) {
                        slowQueryMetadata.setTimestamp(line);
                    }
                    if (line.toLowerCase().trim().startsWith("insert") || line.toLowerCase().trim().startsWith("delete") || line.toLowerCase().trim().startsWith("update") || line.toLowerCase().trim().startsWith("select")) {
                        StringBuilder sql = new StringBuilder(line);
                        while (i < list.size() - 1) {
                            i++;
                            line = list.get(i);
                            if (line.startsWith("# Time: ")) {
                                i--;
                                break;
                            }
                            if (StringUtils.hasText(line) && !line.trim().startsWith("--")) {
                                sql.append(line);
                            }
                        }
                        slowQueryMetadata.setSql(sql.toString());
                        break;
                    }

                }


            }
        }
        return slowQueryMetadataList;
    }

    private static void evaluationAppName(String line, SlowQueryMetadata slowQueryMetadata) {
        try {
            // # User@Host: root[root] @  [192.168.100.101]  Id: 13523930
            String ip = line.substring(line.lastIndexOf("[")+1,line.lastIndexOf("]"));

            Map<String, String> appMap = getAppMap();
            String appName = appMap.get(ip);
            if (!StringUtils.hasText(appName)) {
                appName = "未知服务";
            }
            slowQueryMetadata.setAppName(appName);
        } catch (Exception e) {
            slowQueryMetadata.setAppName("异常服务");
        }

    }
    private static Map<String, String> getAppMap() {
        Map<String, String> appMap = new HashMap<>();
        appMap.put("10.39.77.34", "enn-smart-operation-project-web");
        appMap.put("10.39.77.78", "enn-smart-websocket-web");
        appMap.put("10.39.77.35", "enn-smart-operation-station-web");
        appMap.put("10.39.77.33", "enn-smart-operation-pipeline-web");
        appMap.put("10.39.77.99", "enn-smart-supervision-web");
        appMap.put("10.39.77.31", "enn-smart-operation-customer-web");
        appMap.put("10.39.77.97", "enn-smart-operation-energy-web");
        appMap.put("10.39.77.109", "enn-smart-job-executor-operation-energy");
        appMap.put("10.39.77.38", "enn-smart-job-executor-operation-common");
        appMap.put("10.39.77.107", "enn-smart-job-executor-operation-project");
        appMap.put("10.39.77.106", "enn-smart-job-executor-operation-customer");
        appMap.put("10.39.77.39", "enn-smart-operation-web");
        appMap.put("10.39.77.105", "enn-smart-job-executor-operation-pipeline");
        appMap.put("10.39.77.104", "enn-smart-job-executor-operation-station");
        appMap.put("10.39.77.15", "enn-smart-video-web,enn-smart-screen-web");
        appMap.put("10.39.89.9", "enn-smart-gateway");
        appMap.put("10.39.77.135", "enn-smart-operation-emq-receiver");
        appMap.put("10.39.84.96", "enn-smart-xs-web");
        appMap.put("10.39.77.153", "enn-smart-gateway");
        appMap.put("10.39.88.75", "enn-smart-standard-web");
        appMap.put("10.39.77.64", "enn-smart-emergency-web");
        appMap.put("10.39.77.93", "enn-smart-interface-web");
        appMap.put("10.39.77.91", "enn-smart-api-gateway");
        appMap.put("10.39.84.77", "enn-smart-monitor-gz-web");
        appMap.put("10.39.88.16", "enn-smart-mobile-web");
        appMap.put("10.39.77.87", "enn-smart-job-executor-operation-emergency");
        appMap.put("10.39.77.66", "enn-smart-export-web");
        appMap.put("10.39.88.44", "enn-smart-registry");
        appMap.put("10.39.77.117", "enn-smart-emergency-web");
        appMap.put("10.39.77.25", "enn-smart-ability-web");
        appMap.put("10.39.77.116", "enn-smart-screen-kg-web");
        appMap.put("10.39.77.16", "enn-smart-operation-emq-receiver");
        appMap.put("10.39.77.103", "enn-smart-supervision-gateway");
        appMap.put("10.39.77.14", "enn-smart-operation-web");
        appMap.put("10.39.77.144", "enn-smart-registry");
        appMap.put("10.39.84.68", "enn-smart-monitor-cz-web");
        appMap.put("10.39.77.9", "enn-smart-obs-web");
        appMap.put("10.39.77.73", "enn-smart-screen-web");
        appMap.put("10.39.77.8", "enn-smart-uid-web");
        return appMap;
    }


}

